import Vuex from 'vuex'

const setLocalCartList = (state) => {
  const { cartList } = state
  localStorage.carList = JSON.stringify(cartList)
}
const getLocalCartList = () => {
  // { shopId: {shopName:'', productList:{ productId: {} }}}
  try {
    return JSON.parse(localStorage.cartList)
  } catch (e) {
    return {}
  }
}

export default Vuex.createStore({
  state: {
    cartList: getLocalCartList()
    // cartList: {
    //   // shopId: {
    //   //   shopName: 'xxx',
    //   //   productList: {
    //   //     productId: {
    //   //       _id: '',
    //   //       name: 'xxx'
    //   //     }
    //   //   }
    //   // }
    //   // 第一层是商铺ID
    //   // shopId
    //   // 第二层是商品ID
    //   // 第二层是商品内容以及购物数量
    // }

  },
  mutations: {
    changeCartItemInfo (state, payload) {
      const { shopId, productId, productInfo } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      let product = shopInfo.productList[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo
      }
      product.count = product.count + payload.number
      if (payload.number > 0) {
        product.check = true
      }
      if (product.count < 0) {
        product.count = 0
      }
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartItemChecked (state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLocalCartList(state)
    },
    clearProductCarts (state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },
    setCartItemChecked (state, payload) {
      const { shopId } = payload
      const productList = state.cartList[shopId].productList
      if (productList) {
        for (const i in productList) {
          const product = productList[i]
          product.check = true
        }
      }
      setLocalCartList(state)
    },
    clearCartData (state, shopId) {
      state.cartList[shopId].productList = {}
    },
    changShopName (state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    }
  },
  actions: {},
  modules: {}
})
